var swiper = null;
var tis_perty_ui = function () {
    var tisApp, temp;
    function onInitUI(container,options) {
        var tis_html =
        '<div class="tis-center-box">\
            <div class="tis-msgs-panel"></div>\
            <div class="tis-tools-panel" style="display:none">\
                <div class="tis-tools-panel disableSelect">\
                    <div class="tis-faces-box">\
                        <div class="tis-faces-swiper">\
                            <div class="swiper-wrapper"><div class="swiper-slide"></div></div>\
                            <div class="swiper-pagination"></div>\
                        </div>\
                        <div class="tis-facegroups"></div>\
                    </div>\
                </div>\
            </div>\
        </div>\
        <div class="tis-bottom-panel">\
            <div class="tis-sendText-wrap">\
                <textarea class="tis-sendText" placeholder="请输入内容"></textarea>\
            </div>\
            <div class="tis-tools-bar">\
            <a class="tis-face-btn"></a>\
            </div>\
            <a class="tis-sendBtn">发送</a>\
        </div>';
        $(container).html(tis_html);
        $(".tis-top-name").html(options.hits);
        // $(".tis-top-name").width($(".tis-top-name").parent().width() - 70);
        $(".tis-center-box").height(
                $(".tis-container").height() -
                $(".tis-top-bar").height() - $(".tis-bottom-panel").height() - 1);
        //$(".tis-sendText-wrap").width($(".tis-bottom-panel").width() - $(".tis-sendBtn").width() - 25);
        $(".tis-sendText-wrap").width('64%');

        function hideToolPanel() {
            $(".tis-msgs-panel").height($(".tis-msgs-panel").parent().height());
            $(".tis-tools-panel").hide();
            $(".tis-msgs-panel").scrollTop($(".tis-msgs-panel")[0].scrollHeight);
            $(".tis-msgs-panel").parent().scrollTop($(".tis-msgs-panel").parent()[0].scrollHeight);
        }
        function showToolPanel() {
            if ($(".tis-tools-panel").parent().height() > 125) {
                $(".tis-msgs-panel").height($(".tis-tools-panel").parent().height() - 125);
                $(".tis-tools-panel").css("height", "125px");
            } else {
                $(".tis-msgs-panel").height(0);
                $(".tis-tools-panel").height($(".tis-tools-panel").parent().height());
            }
            $(".tis-tools-panel").show();
        }
        $(".tis-tools-bar a").click(function (e) {
            if ($(".tis-tools-panel").css("display") == "none") {
                showToolPanel();
            } else {
                hideToolPanel();
            }
            if (!swiper) {
                swiper = new Swiper('.tis-faces-swiper', {
                    pagination: '.swiper-pagination',
                    paginationClickable: true
                });
                if ($(container + " .tis-facegroups").children().length > 0) {
                    $(container + " .tis-facegroups").children()[0].click();
                }
            }
        });
        
        $(container + " .tis-sendText").mousedown(hideToolPanel);
        function sendMessage() {
            tisApp = tisApp ? tisApp : window.tis;
            hideToolPanel();
            var sendText1 = $(container + " .tis-sendText").val();
			var sendText  = sendText1.replace(/\s+/g, "");
			if(localStorage.getItem('token')){
				if(sendText==''){
					// alert("请输入内容");
					layer.open({
						content: '请输入内容',
						skin: 'msg',
						time: 2 //1秒后自动关闭
					});
					return;
				}
				if (sendText.length > 1000) {
					// alert("发送内容太长啦");
					layer.open({
						content: '发送内容太长啦',
						skin: 'msg',
						time: 2 //1秒后自动关闭
					});
					return;
				}
				// if()
				tisApp.SendMessage(sendText);
			}else{
				layer.open({
					content: '请先登录',
					skin: 'msg',
					time: 2 //1秒后自动关闭
				});
				return;
			}
            $(container + " .tis-sendText").val("")
        }
        $(container + " .tis-sendText").keydown(function (e) {
            if (e == null || e.keyCode == null || e.ctrlKey == null) return;
            if (e.keyCode == 13 && e.ctrlKey) {
                e.preventDefault();
                sendMessage();
            }
        });
        $(container + " .tis-sendBtn").click(sendMessage);
    }
    function appendTisMessage(msgBox, data, faceMap) {
        if (msgBox.children().length >= temp.maxMesageNum) {
            msgBox.children().eq(0).remove();
        }
        for (var item in faceMap) {
            data.body = data.body.replace(new RegExp("\\" + item, "g"), "<img src='" + faceMap[item] + "'/>");
        }
        var timestr;
        if(data.time) {
            var date = new Date(data.time*1000);
			// console.log(date.getFullYear());
			// console.log(date);
            var minu,sec;
            if (date.getMinutes()<10) minu = "0"+date.getMinutes();
            if (date.getSeconds()<10) sec = "0"+date.getSeconds();
            minu  = minu?minu:date.getMinutes();
            sec = sec?sec:date.getSeconds();
            var now = new Date();
//             if (date.getDate() == now.getDate() ) {
//             	timestr = date.getHours() + ":" + minu + ":" + sec;
//             } else if(now.getDate() - date.getDate() == 1){
//             	timestr = "昨天";
//             }else{
            timestr = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+"  "+date.getHours() + ":" + minu + ":" + sec;
            // }
        }
        var headimg = $("<img src='" + (!!data.image ? data.image : "https://cdn.aodianyun.com/tis/ui/perty/img/anonymous2.png") + "'/>");
        var namelabel = $("<span class='tis-msg-name'>" + data.name + "：</span>");
        var timelabel = $("<p>" + timestr + "</p>");
        var div = $("<div class='tis-msg-head'></div>").append(headimg).append(namelabel).append(timelabel);
        if (msgBox.width() < 180) {
            namelabel.width(msgBox.width() - 10 - 8 - 32 - 10);
            timelabel.html("");
        } else {
            namelabel.width(msgBox.width() - 10 - 8 - 32 - 60 - 10);
        }
        msgBox.append($("<a></a>").append(div).append("<div class='tis-msg-body'>" + data.body + "</div>"));
        if ($(".tis-tools-panel").css("display") != "none") {
            showToolPanel();
        } else {
            msgBox.height(msgBox.parent().height());
        }
        msgBox.scrollTop(msgBox[0].scrollHeight);
        msgBox.parent().scrollTop(msgBox.parent()[0].scrollHeight);
    }
    function onReceiveMessage(data, container, faceMap) {
        var msglist = $(container + " .tis-msgs-panel");
        appendTisMessage(msglist, data, faceMap);
    }
    function onLoadHistory(data, container, faceMap , opts) {
        var msglist = $(container + " .tis-msgs-panel");
        var list = data.list;
        var length = 0;
        if (list) {
            length = list.length;
        }
        for (var index = length - 1; index >= 0; --index) {
            var item = list[index];
            if (!item.content) continue;
            var msgdata;
            try {
                msgdata = JSON.parse(item.content);
                msgdata = opts.prepareMessage(msgdata);
                appendTisMessage(msglist, msgdata, faceMap);
            } catch (ex) { }
        }
    }
    function onLoadGroup(data, container, groupClicked) {
        var groups = $(container + " .tis-facegroups");
        for (var index in data) {
            var item = data[index];
            var group = $('<a gid="' + item.id + '" ><img src="' + item.icon + '" /></a>');
            group.click(function () {
                $(container + " .swiper-wrapper").html("");
            });
            group.click(groupClicked);
            groups.append(group);
        }
    }
    function onLoadFaces(keys, faceMap, container, groupId) {
        var i = 0, pageSize = 24;
        var pagePanel = $(container + " .swiper-wrapper").append('<div class="swiper-slide"></div>').children().last();
        for (var index = 0; index < keys.length; index++) {
            var item = keys[index];
            pagePanel.append($("<a text='" + item + "'><img src='" + faceMap[item] + "' /></a>").click(function () {
                var sendText = $(container + " .tis-sendText");
                sendText.val(sendText.val() + $(this).attr("text"));
            }));
            if (++i >= pageSize) {
                i = 0;
                pagePanel = $(container + " .swiper-wrapper").append('<div class="swiper-slide"></div>').children().last();
            }
        }
        for (; i < pageSize; i++) {
            pagePanel.append("<a class='noneFace'></a>");
        }
        swiper.swipeTo(0, 0, false);
        swiper.reInit();
    }
    temp = {
        onInitUI: onInitUI,               //必须，在这个时机去初始化界面
        onLoadHistory: onLoadHistory,          //可选，加载历史消息时调用，不填则不加载
        onLoadGroup: onLoadGroup,            //加载分组完毕时调用
        onLoadFaces: onLoadFaces,            //加载表情完毕时调用
        onReceiveMessage: onReceiveMessage,         //收到消息时调用
        onPreSendMessage: function (msg) { return true },         //发送消息之前调用
        setTisApp: function (_tisApp) {
            tisApp = _tisApp;
        },
        historyPageSize: 50,                        //加载历史消息的条数
        maxMesageNum: 50,
        version: 1.2                                //模版版本
    }
    return temp;
}();
